/* 
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var Items = {
    /* Server script url   */
    $thisObj:null,
    ssUrl:'',
    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;
        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();
        self.ssUrl = $('#add-edit-url').val();

        self.bindRepaymentBtn();

        Calendar.setup({
            inputField : "pay_date",
            trigger    : "pay_date_btn",
            onSelect   : function() { this.hide() },
            dateFormat: "%B %d, %Y",
            showTime: false,
            animation: true
        });

        Items.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Purchased Date', name:'purchased_date', width:100, sortable:true, align:'center', hide:false},
                {display:'Customer', name:'customer_id', width:170, sortable:true, align:'center', hide:false},
                {display:'Sales No.', name:'vehicle_no', width:100, sortable:true, align:'center', hide:false},
                {display:'Vehicle No.', name:'vehicle_no', width:100, sortable:true, align:'center', hide:false},
                {display:'Opening Bal', name:'open_bal', width:170, sortable:false, align:'center', hide:false},
                {display:'Installment', name:'installment', width:100, sortable:false, align:'center', hide:false},
                {display:'Total Repayment', name:'total_installment', width:110, sortable:false, align:'center', hide:false},
                {display:'Balance', name:'balance', width:80, sortable:false, align:'center', hide:false}
            ],
            formFields:[
                /*{type:'buttom',name: 'Add', bclass: 'add', onpress : Items.handleGridEvent},
                 {separator: true},*/
                {type:'buttom', name:'Edit Repayment', bclass:'edit', onpress:self.handleGridEvent},
                {separator:true},
                {type:'select', name:'Select Customers', id:'select_customer', bclass:'person', options:gbl_customers_sales, onchange:self.handleGridEvent}
            ],
            searchitems:[
                {display:'Name', name:'name', isdefault:true}
            ],
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            onSubmit:self.addFormData,
            height: 300
        });

        $('#save-btn').click(function () {
            self.save();
        });

        $('#cancel-btn').click(function () {
            document.getElementById('form').reset();
            $.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
            self.selected_row_id = null;
            $('#form #amt_tendered_rate_txt span b').html('0.00');
            $("#repayment_inner_block").hide();
        });

        jLib.afterClosePopUpForm('form', function () {
            self.selected_row_id = null;
            document.getElementById('form').reset();
            $('#form #amt_tendered_rate_txt span b').html('0.00');
            $("#repayment_inner_block").hide();
        });

        $("#form").validationEngine();

        $('#form #original_paid_amount').focusout(function () {
            var currency = $('#form #currency').val();
            var deposit_currency = $('#form #paid_amount_currency').val();
            var amount = $('#form #original_paid_amount').val();
            var usd_rate = $('#form #usd_rate').val();
            self.getDeposit(currency, deposit_currency, amount, usd_rate);
        });
        $('#form #paid_amount_currency').change(function () {
            var currency = $('#form #currency').val();
            //var deposit_currency = $('#form #paid_amount_currency').val();
            var amount = $('#form #original_paid_amount').val();
            var usd_rate = $('#form #usd_rate').val();
            self.getDeposit(currency, $(this).val(), amount, usd_rate);
        });
    },

    handleGridEvent:function (com, grid,json) {
        if (com == 'Add') {
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                title:'Items Information',
                href:"#form-window"
            });
        }
        else if (com == 'Edit Repayment') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                Items.edit(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Select Customers') {
            Items.filterCustomers(json);
        }
    },

    filterCustomers:function (value) {
        var self = this;
        console.log(value);
        self.objGrid.flexOptions({params:[
            {name:'customer_id', value:value}
        ]}).flexReload();

        console.log(value);
        return false;
    },

    addFormData:function () {
        var self = this;
        var val = $("#select_customer").val();
        console.log(val);
        //self.objGrid.flexOptions({params: [{name:'customer_id',value:val}]});
        $('#flex').flexOptions({params:[
            {name:'customer_id', value:val}
        ]});
        return true;
    },


    getDeposit:function(currency, deposit_currency, deposit_value, usd_rate){
        var self = this;

        //console.log(currency);
        //console.log(deposit_currency);
        //console.log(deposit_value);
        //console.log(usd_rate);

        if(deposit_currency == currency){
            $('#form #amt_tendered_rate_txt').hide();
            $('#form #conversion_rate_txt').hide();
        }
        else{
            if(currency == '$' && deposit_currency == 'GHc'){//Covert to dollar
                deposit_value = deposit_value / usd_rate;
            }
            else if(currency == 'GHc' && deposit_currency == '$'){//Convert to Cedi
                deposit_value = deposit_value * usd_rate;
            }
            $('#form #amt_tendered_rate_txt span b').html(''+currency+' '+jLib.formatNumber(deposit_value,'money'));
            $('#form #amt_tendered_rate_txt').show();
            $('#form #conversion_rate_txt').show();
        }
        $('#form #paid_amount').val(deposit_value)

        $.colorbox.resize();

        return deposit_value
    },



    edit:function (row_ids) {
        var self = this;
        var dataID = row_ids[0];
        var url = $('#load-user-url').val();
        var query = 'type=load&data-id=' + dataID;

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    var dataObj = response.data.SaleCreditPayment;
                    var currency = response.data.Sale.currency;
                    //console.log(dataObj);

                    var tbody = $("table#repayment_detail_tbl_list tbody");
                    tbody.html('');

                    for(var x in dataObj){
                        var repay_id = dataObj[x]['id'];
                        var pay_date = dataObj[x]['pay_date'];
                        var original_paid_amount = dataObj[x]['original_paid_amount'];
                        var paid_amount_currency = dataObj[x]['paid_amount_currency'];
                        var usd_rate = dataObj[x]['usd_rate'];
                        var pay_amount = dataObj[x]['paid_amount'];
                        var pay_type = dataObj[x]['pay_type'];
                        var comments = dataObj[x]['comments'];

                        var tr = $("<tr />").attr('data-id',repay_id).attr('currency',currency).attr('original_paid_amount',original_paid_amount).attr('paid_amount_currency',paid_amount_currency).attr('paid_amount',pay_amount).attr('usd_rate',usd_rate);
                        tr.append($("<td />").html(pay_date));
                        /*tr.append($("<td />").html(paid_amount_currency));*/
                        tr.append($("<td />").html(currency+" "+jLib.formatNumber(pay_amount,'money')));
                        tr.append($("<td />").html(pay_type));
                        tr.append($("<td />").html(comments));
                        var img_edit = $("<img />").attr('src',$("#edit-pic-src").val());
                        img_edit.attr('class','edit_repayment_btn');
                        img_edit.attr('title','Edit');
                        var img_del = $("<img />").attr('src',$("#delete-pic-src").val());
                        img_del.attr('class','delete_repayment_btn');
                        img_del.attr('title','Delete');
                        var img_print = $("<img />").attr('src',$("#print-pic-src").val());
                        img_print.attr('class','print_receipt_btn');
                        img_print.attr('title','Reprint Receipt');
                        tr.append($("<td />").append(img_edit).append("&nbsp;").append("&nbsp;").append("&nbsp;").append(img_del).append("&nbsp;").append("&nbsp;").append("&nbsp;").append(img_print));

                        tbody.append(tr);
                    }

                    $("table#repayment_detail_tbl_list tbody tr").live('click',function(){
                        var tr = $(this);
                        $("table#repayment_detail_tbl_list tbody tr").each(function(){
                            $(this).removeClass('clicked');
                        });
                        tr.addClass('clicked')
                    });

                    self.getDeposit('$', '$', 0.00, 0.00);

                    Items.selected_row_id = self;

                    $.colorbox({
                        inline:true,
                        scrolling:false,
                        overlayClose:false,
                        escKey:false,
                        title:'Repayments Information',
                        href:"#form-window"
                    });

                    $.colorbox.resize();
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });

    },

    bindRepaymentBtn:function(){
        var self = this;
        $("table#repayment_detail_tbl_list tbody tr td img").live('click',function(){
            var tr = $(this).parent().parent();
            var repay_id = tr.attr('data-id');

            var class_ = $(this).attr('class');
            if(class_ == 'edit_repayment_btn'){
                var pay_date = tr.find('td:nth-child(1)').html();
                var original_paid_amount = tr.attr('original_paid_amount');
                var paid_amount_currency = tr.attr('paid_amount_currency');
                var usd_rate = tr.attr('usd_rate');
                var paid_amount = tr.attr('paid_amount');
                var pay_type = tr.find('td:nth-child(3)').html();
                var comments = tr.find('td:nth-child(4)').html();

                var currency = tr.attr('currency');

                $("#repayment_inner_block").show();
                //console.log(usd_rate);
               // $("#amt_tendered_txt").html("Amount Tendered "+currency+":");

                $('#form-window #form #currency').val(currency);
                $('#form-window #form #paid_amount_currency').val(paid_amount_currency);
                $('#form-window #form #paid_amount_currency').change();
                $('#form-window #form #original_paid_amount').val(original_paid_amount);
                $('#form-window #form #usd_rate').val(usd_rate);
                $('#form-window #form #paid_amount').val(paid_amount);
                $('#form-window #form #pay_date').val(jLib.convertDate(pay_date,'ui'));
                $('#form-window #form #pay_type').val(pay_type);
                $('#form-window #form #pay_type').change();
                $('#form-window #form #comments').val(comments);
                $('#form-window #form #id').val(repay_id);

                self.getDeposit(currency, paid_amount_currency, original_paid_amount, usd_rate);
            }
            else if(class_ == 'delete_repayment_btn'){
                self.delete_(repay_id, tr);
            }
            else{
                self.reprint_receipt(repay_id, tr);
            }
        });
    },

    save:function () {
        var self = this;
        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            var amt = $("#form #original_paid_amount").val();
            if(amt == 0){
                jLib.setFeedback("The amount tendered must be greater than 0", 'error_message', false);
                return false;
            }

            jLib.showFormLoading();

            var query = 'model=SaleCreditPayment&row_id=' + self.selected_row_id + '&' + $('#form').serialize();
            /* Send the data to the server and handle the server response */
            var url = $("#add-edit-url").val();

            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {
                        if(self.selected_row_id){

                            jLib.message(txt, 'success');

                            /*update_data = {
                             'name': $('#form-window #form #name').val(),
                             'currency': $('#form-window #form #currency').val(),
                             'amount': $('#form-window #form #amount').val(),
                             'interest': $('#form-window #form #interest').val(),
                             'comments':$('#form-window #form #comments').val()
                             };
                             jLib.updateGridData(Items.objGrid, update_data);
                             //
                             jLib.highlightRow(Items.objGrid);*/
                            $(self.objGrid).flexReload();
                        }
                        else{
                            $(self.objGrid).flexReload();

                        }
                        document.getElementById('form').reset();
                        $.validationEngine.closePrompt('.formError',true);
                        $.colorbox.close();
                        self.selected_row_id = null;
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    },


    delete_:function (id, tr) {
        var self = this;
        var url = $('#delete-url').val();
        $.modal.confirm('Are you sure you want to continue ?', function () {
            $.post(url, {'ids[]':id}, function (response) {
                //delete was successful, remove checkbox rows
                if (response.code == 0) {
                    tr.remove();
                    jLib.message(response.mesg, 'success');
                    //jLib.setFeedback(response.mesg, 'success_message', false);
                }
                else if (response.code == 1) {
                    jLib.message(response.mesg, 'error');
                }
            }, "json");

        }, function () {
            //$.modal.alert('Meh.');
        });

    },


    reprint_receipt:function (id, tr) {
        //Initate print reciept

        var action = $('#print-receipt-url').val();
        var url = action+'/'+id;

        window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
    }

};

/* when the page is loaded */
$(document).ready(function () {
    Items.init();
});